<template>
  <div class="main officialUser">
    <div v-if="rightsButtons['add']" class="tool-bar">
      <el-button type="success" icon="el-icon-plus" class="fr" @click="addButton">新建</el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="给我一点时间" header-row-class-name="table-header" border highlight-current-row>
      <el-table-column align="center" label="手机号" prop="mobile"></el-table-column>
      <el-table-column align="center" label="昵称" prop="nickName"></el-table-column>
      <el-table-column align="center" label="头像" prop="headImgUrl">
        <template slot-scope="scope">
          <img :src="scope.row.headImgUrl?scope.row.headImgUrl:'https://asset.bisinuolan.cn/bixuan_uni/images/logo.png'" style="width:50px;height:50px;">
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="260">
        <template slot-scope="scope">
          <el-button v-if="rightsButtons['remove']" type="danger" size="mini" plain @click="del(scope.row)">移除官方</el-button>
          <el-button v-if="rightsButtons['viewDetails']" type="primary" size="mini" plain @click="$router.push({name: 'officialUserViewDetails', params: {id: scope.row.userDBId}})">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增弹框 -->
    <el-dialog title="新增用户" :visible.sync="showAddDialog" :before-close="handleClose" center>
      <el-form ref="mobileRef" :model="mobileForm" :rules="mobileRule" size="medium" label-width="120px">
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="mobileForm.mobile" type="tel"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addConfirm">确认</el-button>
      </div>
    </el-dialog>
    <!-- 确认移除并转移弹框 -->
    <el-dialog :title="`确定从官方号移除${removeMobile}账户`" :visible.sync="removeDialog" center>
      <el-form ref="form" size="medium" label-width="120px">
        <span class="confirmSpan">已关联文章需选择转移到另外一个官方账户下</span>
        <el-form-item label="帖子转移用户:">
          <el-select v-model="confirmToUser">
            <el-option v-for="item in toUsers" :key="item.id" :label="`${item.nickName}--${item.mobile}`" :value="item.mobile"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmDelAndTransfer">确认移除</el-button>
        <el-button type="primary" @click="cancelTransfer">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { regexp } from '../../../utils/tools'
export default {
  name: 'OfficialUser',
  data() {
    const validTel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'))
      }
      if (!regexp.tel.test(value)) {
        return callback(new Error('手机号格式错误'))
      }
      callback()
    }
    return {
      list: [],
      listQuery: {},
      toUsers: [],
      confirmToUser: '',
      removeMobile: '',
      listLoading: false,
      showAddDialog: false,
      removeDialog: false,
      mobileForm: {
        mobile: ''
      },
      mobileRule: {
        mobile: [
          { required: false, message: '不能为空', trigger: 'change' },
          { pattern: regexp.tel, message: '手机号格式错误', trigger: 'change' },
          { validator: validTel, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.request({
        url: '/zhongcao-web-manage/account/list',
        method: 'get'
      }).then((res) => {
        this.list = res.data
        this.listLoading = false
      }).catch(err => {
        this.list = []
        this.listLoading = false
      })
    },
    // 新增按钮
    addButton() {
      this.showAddDialog = true
    },
    handleClose(){
      this.showAddDialog = false
      this.mobileForm.mobile=''
    },
    // //新增用户确认
    addConfirm() {
      this.$refs['mobileRef'].validate(valid => {
        if (!valid) {
          return false
        }
        this.request({
          url: '/zhongcao-web-manage/account/add',
          method: 'post',
          data: {
            mobile: this.mobileForm.mobile
          }
        }).then(() => {
          this.mobileForm.mobile = ''
          this.showAddDialog = false
          this.$message.success('保存成功')
          this.getList()
        }).catch(err => {
          console.log(err)
        })
      })
    },
    del(row) {
      this.toUsers = this.list.filter(item => row.mobile !== item.mobile)
      this.$confirm(`确定从官方号移除 ${row.mobile} 账户?`, '', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        center: true
      }).then(() => {
        this.request({
          url: '/zhongcao-web-manage/account/deleteConfirm',
          method: 'get',
          params: {
            deleteUserId: row.userId
          }
        }).then((res) => {
          // 当data为false
          if (!res.data) {
            if (this.toUsers.length === 0) {
              this.$confirm('当前无法转移到另外一个官方账户下', '', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                center: true
              }).then(() => {
                this.getList()
              })
            } else {
              this.removeDialog = true
              this.removeMobile = row.mobile
              this.confirmToUser = this.toUsers[0].mobile
            }
          } else {
            this.$message.success('移除成功')
            this.getList()
          }
        }).catch(err => {
          console.log(err)
          this.removeDialog = false
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 确认移除并转移
    confirmDelAndTransfer() {
      this.request({
        url: '/zhongcao-web-manage/account/change',
        method: 'post',
        data: {
          mobileIn: this.confirmToUser,
          mobileOut: this.removeMobile
        }
      }).then((res) => {
        this.$message.success('移除成功，并已经成功转移')
        this.confirmToUser = ''
        this.removeDialog = false
        this.getList()
      }).catch(err => {
        console.log(err)
      })
    },
    // 取消转移
    cancelTransfer() {
      this.confirmToUser = ''
      this.removeDialog = false
    }
  }
}
</script>
<style lang="scss">
  .confirmSpan{
    display: block;
    margin-bottom: 20px;
    text-align: center;
  }
</style>
